package shun.demo.remote.display.client;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import shun.demo.R;
import shun.demo.remote.touch.client.InputClient;
import shun.demo.remote.touch.model.MyMotionEvent;

import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * Created by chen on 14-4-26.
 */
public class ConnectActivity extends Activity implements View.OnClickListener {

    private EditText mAddressText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.connect);
        mAddressText = (EditText) findViewById(R.id.address);
        mAddressText.setSelection(mAddressText.getText().length());
    }

    private class ConnectTask extends AsyncTask<String, Void, Boolean> {

        private ProgressDialog mProgressDialog;

        @Override
        protected void onPreExecute() {
            mProgressDialog = new ProgressDialog(ConnectActivity.this);
            mProgressDialog.show();
        }

        @Override
        protected Boolean doInBackground(String... params) {
            try {
                XScreen.get().connect(params[0]);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean connected) {
            if (mProgressDialog.isShowing()) {
                try {
                    mProgressDialog.dismiss();
                } catch (Exception e) {
                }
            }
            String text;
            if (connected) {
                XScreenActivity.start(ConnectActivity.this);
                text = "Connect success";
            } else {
                text = "Connect failed";
            }
            Toast.makeText(ConnectActivity.this, text, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        String string;
        switch (v.getId()) {
            case R.id.connect:
                string = mAddressText.getText().toString().trim();
                new ConnectTask().execute(string);
                break;
        }
    }
}
